package com.th.apicenter.mi.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.th.apicenter.deduct.entity.ThDeduct;
import com.th.apicenter.kuaishou.service.KuaiShouService;
import com.th.apicenter.mapper.ThDeductMapper;
import com.th.apicenter.mapper.ThMiDataMapper;
import com.th.apicenter.mi.dto.ThMiNumDTO;
import com.th.apicenter.mi.entity.ThMiData;
import com.th.apicenter.tools.ThTools;
import com.th.apicenter.tools.OkhttpClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
@Slf4j
public class MiService {

    @Resource
    private ThMiDataMapper thMiDataMapper;

    @Resource
    private ThDeductMapper thDeductMapper;

    @Resource
    private KuaiShouService kuaiShouService;

    private final String mi_callback = "https://trail.e.mi.com/api/callback";

    /**
     * 20250428 小米的目前只做真回传
     *
     * @param thMiData
     */
    public String receive(ThMiData thMiData) {
        thMiData.setCreateTime(new Date());
        thMiData.setUpdateTime(new Date());
        thMiDataMapper.insert(thMiData);
        log.info("小米检测接收到的数据：{}", thMiData);
        //判断是否回传
        ThDeduct thDeduct = thDeductMapper.selectOne(new QueryWrapper<ThDeduct>()
                .eq("type", "mi")
                .eq("account_id", thMiData.getAccountId()));
        if (null != thDeduct && thDeduct.getIsTrue() == 0) {
            kuaiShouService.clickMi(thMiData, thDeduct);
        }
        return "数据已接收";
    }

    public void callback(String actionType, String MiId) {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String date = formatter.format(currentTime);
        String startTime = date + " 00:00:00";
        String endTime = date + " 23:59:59";

        ThMiData thMiData = thMiDataMapper.selectById(MiId);
        if ("1300482".equals(thMiData.getAccountId())) {
            if ("1".equals(actionType)){
                if (null != thMiData) {
                    thMiData.setIsKsCallback(1);
                    ThDeduct thDeduct = thDeductMapper.selectOne(new QueryWrapper<ThDeduct>()
                            .eq("type", "mi")
                            .eq("account_id", thMiData.getAccountId()));
                    //判断是否扣量
                    ThMiNumDTO thMiNumDTO = thMiDataMapper.queryNumByDate(thMiData.getAccountId(), startTime, endTime);
                    if (thMiNumDTO.getPassbackNum() >= 10) {
                        BigDecimal x = new BigDecimal(thMiNumDTO.getPassbackNum()).divide(new BigDecimal(thMiNumDTO.getEffectiveNum()), 2, RoundingMode.CEILING);
                        BigDecimal percent = new BigDecimal(thDeduct.getPercent()).divide(new BigDecimal(100), 2, RoundingMode.CEILING);
                        if (percent.doubleValue() != 0 && new BigDecimal(1).subtract(x).compareTo(percent) < 0) {
                            log.info("需要扣量，不做操作!");
                            thMiData.setIsDeduct(1);
                        } else {
                            callbackMi(actionType, thMiData);
                            thMiData.setIsMiPassback(1);
                        }
                    } else {
                        callbackMi(actionType, thMiData);
                        thMiData.setIsMiPassback(1);
                    }
                    thMiData.setUpdateTime(new Date());
                    if (null == thMiData.getKsActionType()) {
                        thMiData.setKsActionType(actionType);
                    } else if (null != thMiData.getKsActionType() && null == thMiData.getKsActionTypeO()) {
                        thMiData.setKsActionTypeO(actionType);
                    } else if (null != thMiData.getKsActionType() && null != thMiData.getKsActionTypeO() && null == thMiData.getKsActionTypeT()) {
                        thMiData.setKsActionTypeT(actionType);
                    }
                    thMiDataMapper.updateById(thMiData);
                } else {
                    throw new RuntimeException("账户未配置！");
                }
            }
        } else {
            if (null != thMiData) {
                thMiData.setIsKsCallback(1);
                ThDeduct thDeduct = thDeductMapper.selectOne(new QueryWrapper<ThDeduct>()
                        .eq("type", "mi")
                        .eq("account_id", thMiData.getAccountId()));
                //判断是否扣量
                ThMiNumDTO thMiNumDTO = thMiDataMapper.queryNumByDate(thMiData.getAccountId(), startTime, endTime);
                if (thMiNumDTO.getPassbackNum() >= 10) {
                    BigDecimal x = new BigDecimal(thMiNumDTO.getPassbackNum()).divide(new BigDecimal(thMiNumDTO.getEffectiveNum()), 2, RoundingMode.CEILING);
                    BigDecimal percent = new BigDecimal(thDeduct.getPercent()).divide(new BigDecimal(100), 2, RoundingMode.CEILING);
                    if (percent.doubleValue() != 0 && new BigDecimal(1).subtract(x).compareTo(percent) < 0) {
                        log.info("需要扣量，不做操作!");
                        thMiData.setIsDeduct(1);
                    } else {
                        callbackMi(actionType, thMiData);
                        thMiData.setIsMiPassback(1);
                    }
                } else {
                    callbackMi(actionType, thMiData);
                    thMiData.setIsMiPassback(1);
                }
                thMiData.setUpdateTime(new Date());
                if (null == thMiData.getKsActionType()) {
                    thMiData.setKsActionType(actionType);
                } else if (null != thMiData.getKsActionType() && null == thMiData.getKsActionTypeO()) {
                    thMiData.setKsActionTypeO(actionType);
                } else if (null != thMiData.getKsActionType() && null != thMiData.getKsActionTypeO() && null == thMiData.getKsActionTypeT()) {
                    thMiData.setKsActionTypeT(actionType);
                }
                thMiDataMapper.updateById(thMiData);
            } else {
                throw new RuntimeException("账户未配置！");
            }
        }
    }


    private void callbackMi(String actionType, ThMiData thMiData) {
        String event_type = "";
        switch (actionType) {
            case "4":
                event_type = "APP_RE_ACTIVE_WAKE_UP";
                break;
            case "2":
                event_type = "APP_RETENTION";
                break;
            case "1":
                event_type = "APP_ACTIVE";
                break;
        }
        //拼接url
        StringBuffer sburl = new StringBuffer();
        sburl.append(mi_callback);
        sburl.append("?");
        StringBuffer sb = new StringBuffer();

        try {
            String encode = URLEncoder.encode(thMiData.getCallbackUrl(), "UTF-8");
            sb.append("callback=" + encode);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (!ThTools.isNull(thMiData.getImei())) {
            sb.append("&imei=" + thMiData.getImei());
        }
        if (!ThTools.isNull(thMiData.getOaid())) {
            sb.append("&oaid=" + thMiData.getOaid());
        }
        sb.append("&conv_time=" + thMiData.getClickTime());

        sb.append("&convType=" + event_type);
        sburl.append(sb);

        log.info("回传小米的url：{}", sburl.toString());
        /**
         * {"success":true,"code":0,"failMsg":""}
         */
        String miResult = OkhttpClient.httpGet(sburl.toString());
        log.info("小米回传的接口返回：{}", miResult);

    }


}


